/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-15 12:19:45
 * @LastEditors: zhouhai zhouhaib@yonyou.com
 * @LastEditTime: 2025-04-10 15:13:39
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useEffect, useRef, useState } from 'react'
import { getDictDatasByDictTypes } from '@/api/system/dictData';
import { Button, Popconfirm, Space } from 'antd';
import { DictDataDomain } from '@/type.d/system/dictData';
import ResizeTable from '@/components/ResizeTable';
import { pageInfo } from '@/type.d/ajaxResult';
import PageDiv from '@/components/PageDiv';
import { useStore } from '@/store';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    QueryFilter} from '@ant-design/pro-components';
import {
    listDictData,
    delDictData,
} from '@/api/system/dictData';
// import './index.less';
import { optionselect } from '@/api/system/dictType';
import { DictTypeDomain } from '@/type.d/system/dictType';
import DictDataCard from './dictDataCard';
import { useParams  } from 'react-router-dom';


const DictData: React.FC = () => {
    const { layoutStore } = useStore();
    // const location = useLocation()
    // const { state: routeState } = location;
    let params = useParams();

    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<DictDataDomain>>();
    const [queryValue, setQueryValue] = useState<DictDataDomain>({});
    const [tableListDataSource, setTableListDataSource] = useState<DictDataDomain[]>([]);
    const [sysNormalDisableOptions, setSysNormalDisableOptions] = useState<any[]>([]);

    const [cardData, setCardData] = useState<DictTypeDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);

    const [newdata,setNewdata] = useState<DictDataDomain>({ status: '0' })

    const [dictTypes, setDictTypes] = useState<any[]>([]);


    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });

    /**
     * 列表字段配置
     */
    const columns: ProColumns<DictDataDomain>[] = [
        {
            title: '字典排序',
            dataIndex: 'dictSort',
            valueType: 'digit',
            align: 'left',
            width: '50',
        },
        {
            title: '字典类型',
            dataIndex: 'dictType',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: dictTypes
            },
        },
        {
            title: '字典标签',
            dataIndex: 'dictLabel',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '字典键值',
            dataIndex: 'dictValue',
            valueType: 'text',
            align: 'left',
            width: '50',
        },

        {
            title: '样式属性',
            dataIndex: 'cssClass',
            valueType: 'text',
            align: 'left',
            width: '50',
            hideInTable: true
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: sysNormalDisableOptions
            },
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: DictDataDomain) => [
                <a key="view" onClick={() => {
                    onView(entity)
                }}>详情</a>,
                <a key="edit" onClick={() => {
                    toCard(entity, true)
                }}>修改</a>,
                <a key="delete">
                    <Popconfirm title="确定要删除数据吗？" okText="是" cancelText="否" onConfirm={() => {
                        onDelete(entity)
                    }}>
                        删除
                    </Popconfirm>
                </a>

            ],
        },
    ];

    const toCard = (data: DictTypeDomain, isEdit: boolean = false) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }

    const onView = (data: DictDataDomain) => {
        toCard(data)
    }

    const onDelete = (dedata: DictDataDomain) => {
        if (dedata.dictCode) {
            layoutStore.OpenSpanning()
            delDictData(dedata.dictCode).then(() => {
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.dictCode !== dedata.dictCode
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }


    const headButton = () => {
        return <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => toCard({...newdata, dictType: queryformRef.current?.getFieldValue('dictType')}, true)}
            >
                新增
            </Button>
        </Space>
    }




    useEffect(() => {
        layoutStore.OpenSpanning();
        getDictDatasByDictTypes('sys_normal_disable').then((res) => {
            const data = res.data;
            if (data['sysNormalDisable']) {
                const d: [] = data['sysNormalDisable'];
                setSysNormalDisableOptions(d.map((item: DictDataDomain) => {
                    return {
                        label: item.dictLabel,
                        value: item.dictValue
                    }
                }))

            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })
        layoutStore.OpenSpanning();
        optionselect().then((res) => {
            setDictTypes(res.data.map((item: DictTypeDomain) => {
                return {
                    label: item.dictName,
                    value: item.dictType
                }
            }))
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }, [])


    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])

    useEffect(() => {
        if (params && params.dictType) {
            setNewdata({...newdata,dictType: params.dictType});
            queryformRef.current?.setFieldsValue({...queryValue,dictType: params.dictType})
            queryformRef.current?.submit()
        }
    }, [params,params.dictType])

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,pageInfo.pageSize])

    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        layoutStore.OpenSpanning();
        listDictData({ ..._data, ...pageInfo }).then((res) => {
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };


    return (<PageDiv>{

        pageStatus === 'List' ? <PageDiv>
            <QueryFilter<DictDataDomain>
                defaultCollapsed
                split
                span={4}
                onFinish={(_data) => onQuery({...pageInfo,..._data,current: 1,})}
                formRef={queryformRef}>
                <ProFormSelect
                    key='dictType'
                    name="dictType"
                    options={dictTypes}
                    label="字典类型"
                    onChange={(value)=>{
                        setNewdata({...newdata,dictType: value as any});
                    }}
                    rules={[{
                        required: true,
                        message: '此项为必填项'
                    }]}
                />
                <ProFormText key='dictSort' name="dictSort" label="字典排序" />

                <ProFormText key='dictLabel' name="dictLabel" label="字典标签" />

                <ProFormText key='dictValue' name="dictValue" label="字典键值" />


                <ProFormSelect key='status' name="status"
                    label="状态" options={sysNormalDisableOptions}
                />
            </QueryFilter>
            <ResizeTable<DictDataDomain>
                onRow={record => {
                    return {
                        onDoubleClick: event => {
                            onView(record)
                        },
                    };
                }}
                dataSource={tableListDataSource}
                actionRef={actionRef}
                columns={columns}
                cardBordered
                revalidateOnFocus={false}
                pagination={{
                    ...pageInfo,
                    showTitle: false,
                    onChange: onPageChange
                }}
                headerTitle={headButton()}
                rowKey={'dictCode'}
            >
            </ResizeTable>
        </PageDiv> :
            <DictDataCard
                onBack={() => setPageStatus('List')}
                isedit={isedit}
                setIsedit={setIsedit}
                statusOptions={sysNormalDisableOptions}
                cardData={cardData}
                newdata={newdata}
                tableListDataSource={tableListDataSource}
                setTableListDataSource={setTableListDataSource}
                dictTypes={dictTypes} />}
    </PageDiv>

    )
}
export default DictData;